<template>
  <div id="three"></div>
</template>
<script setup>
//引入threejs
import * as THREE from 'three'
//引入轨道控制器（用来通过鼠标事件控制模型旋转、缩放、移动），没有这个需求可不引入
import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

//引入Vue3生命周期
import { onMounted  } from 'vue'

onMounted(()=>{
  renderFun();
  load();
  animate();
})

let scene = null;
let camera = null;
let renderer = null;
let controls  = null;

const renderFun = () => {
  //场景
  scene = new THREE.Scene()
  scene.background = null;
  const  container = document.getElementById('three');
  //相机
  camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);

  //渲染器
  renderer = new THREE.WebGLRenderer({ alpha: true });
  renderer.setClearColor(0x000000, 0); // 设置背景颜色为透明
  renderer.setSize(container.clientWidth, container.clientHeight);
  container.appendChild(renderer.domElement);
  //
  controls = new OrbitControls(camera, renderer.domElement);
  //
  // // 设置相机位置
  camera.position.set(0, 0, 5);
  //
  // 添加环境光
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambientLight);

  // 添加点光源
  const pointLight = new THREE.PointLight(0xffffff, 1);
  pointLight.position.set(10, 10, 10);
  scene.add(pointLight);

  const spotLight = new THREE.SpotLight(0xffffff, 1);
  spotLight.position.set(15, 40, 35);
  scene.add(spotLight);
}

const load = () => {
  const loader = new ColladaLoader();
  loader.load(
      'https://static-project-01-new1.oss-cn-hangzhou.aliyuncs.com/szcg/mudan/mudan.dae', // 替换为你的 .dae 文件路径
      (collada) => {
        const model = collada.scene;
        // 遍历所有对象，设置材质为双面
        model.traverse((child) => {
          if (child.isMesh) {
            child.material.side = THREE.DoubleSide; // 设置为双面渲染
          }
        });
        // 直接设置模型的缩放
        model.scale.set(0.15, 0.15, 0.15);
        // model.position.set(0, -model.geometry.boundingBox.max.y, 0); // 向下移动模型
        // 将加载的模型添加到场景中
        scene.add(model);
      },
      undefined,
      (error) => {
        console.error('An error happened', error);
      }
  );
}

const animate = () => {
  // 请求下一帧动画
  requestAnimationFrame(animate);
  if (controls) controls.update(); // 更新 OrbitControls
  // 渲染场景
  renderer.render(scene,camera);
}

</script>
<style scoped>
#three {
  width: 100%;
  height: 100vh;
}
</style>
